package manager.auth.utils;
import common.JksUtils;
import common.ResponseEntity;
import manager.customer.service.CustomerAuthService;
import manager.auth.vo.UserInfo;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class ResponseUtils {
    public static  ResponseEntity<UserInfo> getResponse(String token, HttpServletResponse httpServletResponse,String tokenName){
        if (null == token || "".equals(token)) {
            ResponseEntity<UserInfo> response = new ResponseEntity();
            response.setStatusCode(403);
            return response;
        }
        Cookie cookie = new Cookie(tokenName, token);
        cookie.setPath("/");
        cookie.setHttpOnly(true);
        httpServletResponse.addCookie(cookie);
        ResponseEntity<UserInfo> response = new ResponseEntity();
        response.setStatusCode(200);
        return response;
    }
    public static <T> ResponseEntity<UserInfo> virifyCookie(HttpServletRequest request, String tokenName){
        ResponseEntity<UserInfo> responseEntity = new ResponseEntity();
        Cookie[] cookies = request.getCookies();
        String token = "";
        if (cookies == null) {
            responseEntity.setStatusCode(403);
            return responseEntity;
        }
        Boolean hasCookie=false;
        for (Cookie cookie : cookies) {
             if(cookie.getName().equals(tokenName)){
                 hasCookie=true;
             }
        }
        if(!hasCookie){
            responseEntity.setStatusCode(403);
            return responseEntity;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(tokenName)) {
                token = cookie.getValue();
                Map<String,Object> userInfoMap= JksUtils.getUserInfoByToken(token);
                if(userInfoMap==null){
                    responseEntity.setStatusCode(403);
                    return responseEntity;
                }
                String username=(String)userInfoMap.get("username");
                Long userId=Long.parseLong(String.valueOf(userInfoMap.get("userId")));
                UserInfo userInfo=new UserInfo();
                userInfo.setUsername(username);
                userInfo.setId(userId);
                responseEntity.setBody(userInfo);
            }
        }
        return responseEntity;
    }
}
